package com.zenithmind.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenithmind.chat.mapper.AiChatTagMapper;
import com.zenithmind.chat.mapper.AiChatTagRelMapper;
import com.zenithmind.chat.pojo.entity.AiChatTag;
import com.zenithmind.chat.pojo.entity.AiChatTagRel;
import com.zenithmind.chat.pojo.vo.AiChatTagVO;
import com.zenithmind.chat.service.AiChatTagService;
import com.zenithmind.common.security.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * AI对话标签服务实现类
 */
@Service
public class AiChatTagServiceImpl extends ServiceImpl<AiChatTagMapper, AiChatTag> implements AiChatTagService {

    @Autowired
    private AiChatTagRelMapper tagRelMapper;

    @Override
    public String createTag(String tagName, String color) {
        // 检查参数
        if (!StringUtils.hasText(tagName)) {
            throw new RuntimeException("标签名称不能为空");
        }
        
        // 检查是否存在同名标签
        String userId = SecurityUtils.getCurrentUserId();
        LambdaQueryWrapper<AiChatTag> existsWrapper = new LambdaQueryWrapper<>();
        existsWrapper.eq(AiChatTag::getName, tagName)
                    .eq(AiChatTag::getUserId, userId);
        AiChatTag existsTag = this.getOne(existsWrapper);
        if (existsTag != null) {
            return existsTag.getId();
        }
        
        // 创建标签
        AiChatTag tag = new AiChatTag();
        tag.setName(tagName);
        tag.setUserId(userId);
        tag.setUsageCount(0);
        
        // 如果没有指定颜色，生成随机颜色
        if (!StringUtils.hasText(color)) {
            tag.setColor("#" + generateRandomColor());
        } else {
            tag.setColor(color);
        }
        
        this.save(tag);
        return tag.getId();
    }

    @Override
    @Transactional
    public boolean deleteTag(String tagId) {
        // 检查标签是否存在
        AiChatTag tag = this.getById(tagId);
        if (tag == null) {
            return false;
        }
        
        // 检查权限
        String userId = SecurityUtils.getCurrentUserId();
        if (!tag.getUserId().equals(userId)) {
            throw new RuntimeException("无权限操作");
        }
        
        // 删除标签关联
        LambdaQueryWrapper<AiChatTagRel> relWrapper = new LambdaQueryWrapper<>();
        relWrapper.eq(AiChatTagRel::getTagId, tagId);
        tagRelMapper.delete(relWrapper);
        
        // 删除标签
        return this.removeById(tagId);
    }

    @Override
    public boolean updateTag(String tagId, String tagName, String color) {
        // 检查标签是否存在
        AiChatTag tag = this.getById(tagId);
        if (tag == null) {
            return false;
        }
        
        // 检查权限
        String userId = SecurityUtils.getCurrentUserId();
        if (!tag.getUserId().equals(userId)) {
            throw new RuntimeException("无权限操作");
        }
        
        // 更新标签
        if (StringUtils.hasText(tagName)) {
            tag.setName(tagName);
        }
        
        if (StringUtils.hasText(color)) {
            tag.setColor(color);
        }
        
        return this.updateById(tag);
    }

    @Override
    public List<AiChatTagVO> getUserTags(String userId) {
        // 如果没有传入用户ID，使用当前用户ID
        if (!StringUtils.hasText(userId)) {
            userId = SecurityUtils.getCurrentUserId();
        }
        
        // 查询用户标签
        LambdaQueryWrapper<AiChatTag> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiChatTag::getUserId, userId)
              .orderByDesc(AiChatTag::getUsageCount);
        List<AiChatTag> tags = this.list(wrapper);
        
        // 转换为VO
        return tags.stream().map(tag -> {
            AiChatTagVO vo = new AiChatTagVO();
            BeanUtils.copyProperties(tag, vo);
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public Page<AiChatTagVO> getTagPage(Page<AiChatTag> page, String userId) {
        // 如果没有传入用户ID，使用当前用户ID
        if (!StringUtils.hasText(userId)) {
            userId = SecurityUtils.getCurrentUserId();
        }
        
        // 查询标签分页
        LambdaQueryWrapper<AiChatTag> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiChatTag::getUserId, userId)
              .orderByDesc(AiChatTag::getUsageCount);
        Page<AiChatTag> resultPage = this.page(page, wrapper);
        
        // 转换为VO
        Page<AiChatTagVO> voPage = new Page<>(resultPage.getCurrent(), resultPage.getSize(), resultPage.getTotal());
        List<AiChatTagVO> voList = resultPage.getRecords().stream().map(tag -> {
            AiChatTagVO vo = new AiChatTagVO();
            BeanUtils.copyProperties(tag, vo);
            return vo;
        }).collect(Collectors.toList());
        
        voPage.setRecords(voList);
        return voPage;
    }

    @Override
    public List<AiChatTagVO> getChatTags(String chatId) {
        // 查询对话关联的标签ID
        LambdaQueryWrapper<AiChatTagRel> relWrapper = new LambdaQueryWrapper<>();
        relWrapper.eq(AiChatTagRel::getChatId, chatId);
        List<AiChatTagRel> tagRels = tagRelMapper.selectList(relWrapper);
        
        if (CollectionUtils.isEmpty(tagRels)) {
            return new ArrayList<>();
        }
        
        // 获取标签ID列表
        List<String> tagIds = tagRels.stream()
                                    .map(AiChatTagRel::getTagId)
                                    .collect(Collectors.toList());
        
        // 查询标签信息
        List<AiChatTag> tags = this.listByIds(tagIds);
        
        // 转换为VO
        return tags.stream().map(tag -> {
            AiChatTagVO vo = new AiChatTagVO();
            BeanUtils.copyProperties(tag, vo);
            vo.setSelected(true); // 已关联的标签设置为已选中
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    @Transactional
    public boolean addTagsToChat(String chatId, List<String> tagIds) {
        if (CollectionUtils.isEmpty(tagIds)) {
            return true;
        }
        
        // 获取当前用户ID
        String userId = SecurityUtils.getCurrentUserId();
        
        // 检查标签是否存在且用户有权限
        LambdaQueryWrapper<AiChatTag> tagWrapper = new LambdaQueryWrapper<>();
        tagWrapper.in(AiChatTag::getId, tagIds)
                 .eq(AiChatTag::getUserId, userId);
        List<AiChatTag> tags = this.list(tagWrapper);
        
        if (tags.size() != tagIds.size()) {
            throw new RuntimeException("标签不存在或无权限");
        }
        
        // 批量添加关联
        for (AiChatTag tag : tags) {
            // 检查是否已存在关联
            LambdaQueryWrapper<AiChatTagRel> existsWrapper = new LambdaQueryWrapper<>();
            existsWrapper.eq(AiChatTagRel::getChatId, chatId)
                       .eq(AiChatTagRel::getTagId, tag.getId());
            if (tagRelMapper.selectCount(existsWrapper) == 0) {
                // 创建关联
                AiChatTagRel tagRel = new AiChatTagRel();
                tagRel.setChatId(chatId);
                tagRel.setTagId(tag.getId());
                tagRelMapper.insert(tagRel);
                
                // 更新使用次数
                tag.setUsageCount(tag.getUsageCount() + 1);
                this.updateById(tag);
            }
        }
        
        return true;
    }

    @Override
    @Transactional
    public boolean removeTagFromChat(String chatId, String tagId) {
        // 检查参数
        if (!StringUtils.hasText(chatId) || !StringUtils.hasText(tagId)) {
            return false;
        }
        
        // 检查权限
        AiChatTag tag = this.getById(tagId);
        if (tag != null) {
            String userId = SecurityUtils.getCurrentUserId();
            if (!tag.getUserId().equals(userId)) {
                throw new RuntimeException("无权限操作");
            }
        }
        
        // 删除关联关系
        LambdaQueryWrapper<AiChatTagRel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AiChatTagRel::getChatId, chatId)
              .eq(AiChatTagRel::getTagId, tagId);
        int count = tagRelMapper.delete(wrapper);
        
        // 更新标签使用计数
        if (count > 0 && tag != null) {
            tag.setUsageCount(Math.max(0, tag.getUsageCount() - 1));
            this.updateById(tag);
        }
        
        return count > 0;
    }
    
    /**
     * 生成随机颜色
     */
    private String generateRandomColor() {
        Random random = new Random();
        return String.format("%06x", random.nextInt(0xFFFFFF + 1));
    }
} 